import Toast from '@vant/weapp/toast/toast'
import { addGoodsAddress, queryDetail, editGoodsAddress } from '../../api/addressInfoApi'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userJSON: null,
    id: '',
    name: '',
    phone: '',
    area: '',
    detailAddress: '',
    tag: '其它',
    defaultAddressOff: false,
    //新增或修改标识
    addOfEditOff: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(o) {
    const userDataStr = wx.getStorageSync('user_data')
    if (userDataStr == null || userDataStr == '') {
      wx.reLaunch({
        url: '/loginpackage/pages/login/login',
      })
    } else {
      this.setData({
        userJSON: JSON.parse(userDataStr)
      })
      const off = o.off
      this.setData({
        addOfEditOff: off
      })
      if (off == '1') {
        wx.setNavigationBarTitle({
          title: '添加收货地址',
        })
      } else {
        wx.setNavigationBarTitle({
          title: '编辑收货地址',
        })
        const id = o.id
        this.getGoodsAddressDetail(id)
      }
    }
  },

  /**
   * 获取名称
   */
  nameChange(e) {
    this.setData({
      name: e.detail
    })
  },

  /**
   * 获取电话号码
   */
  phoneChange(e) {
    this.setData({
      phone: e.detail
    })
  },
  /**
   * 获取所在地区
   */
  areaChange(e) {
    this.setData({
      area: e.detail
    })
  },
  /**
   * 获取详细地址
   */
  detailAddressChange(e) {
    this.setData({
      detailAddress: e.detail
    })
  },

  /**
   * 获取收货地址详细信息
   */
  getGoodsAddressDetail(id) {
    Toast.loading({
      message: '正在加载...',
      forbidClick: true,
    })
    const params = {
      id: id
    }
    queryDetail(params, res => {
      this.setData({
        id: res.data.id,
        name: res.data.name,
        phone: res.data.phone,
        area: res.data.area,
        detailAddress: res.data.detailAddress,
        tag: res.data.tag,
        defaultAddressOff: res.data.defaultAddressOff == 0 ? false : true
      })
    }, e => {
      console.log(e)
    })

  },

  /**
   * 选择标签
   */
  tagChange(e) {
    this.setData({
      tag: e.detail
    })
  },
  /**
   * 复选框单击事件
   */
  defaultAddressChange(e) {
    this.setData({
      defaultAddressOff: e.detail
    })
  },

  /**
   * 保存按钮
   */
  saveGoodsAddress() {
    Toast.loading({
      message: '正在保存...',
      forbidClick: true,
    })
    //分装参数
    const params = {
      id: this.data.id,
      userId: this.data.userJSON.id,
      name: this.data.name,
      phone: this.data.phone,
      area: this.data.area,
      detailAddress: this.data.detailAddress,
      tag: this.data.tag,
      defaultAddressOff: this.data.defaultAddressOff == true ? 1 : 0
    }
    if (this.data.addOfEditOff == '1') {
      //新增
      addGoodsAddress(params, res => {
        Toast(res.msg)
      }, e => {
        console.log(e)
      })
    } else if (this.data.addOfEditOff == '2') {
      //修改
      editGoodsAddress(params, res => {
        Toast(res.msg)
      }, e => {
        console.log(e)
      })
    }
  },

})